package liu.de.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liude
 */
@Configuration
@Slf4j
public class RabbitMqConfig {
    public static final String QUEUE_TEST = "TEST_QUEUE";
    public static final String EXCHANGE_TEST = "TEST_EXCHANGE";

    public static final String QUEUE_DELAY = "QUEUE_DELAY";

    @Bean
    public Queue testQueue() {
        return new Queue(QUEUE_TEST, true);
    }

    @Bean
    public FanoutExchange testExchange() {
        return new FanoutExchange(EXCHANGE_TEST, true, true);
    }

    @Bean
    public Binding testBinding() {
        return BindingBuilder
                .bind(testQueue())
                .to(testExchange());
    }

    /**
     * 发送消息
     *
     * @param connectionFactory connectionFactory
     * @param objectMapper      objectMapper
     * @return RabbitTemplate
     */
    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory, ObjectMapper objectMapper) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        //发送的时候使用
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter(objectMapper));

        //发送确认
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.info("{},{},{}", correlationData, ack, cause);
        });

        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.info("{},{},{},{},{}", message, replyCode, replyText, exchange, routingKey);
        });
        return rabbitTemplate;
    }
}
